package admin

import (
	"gitee.com/jikey/elk-blog/app/model"
	"gitee.com/jikey/elk-blog/app/service"
	"gitee.com/jikey/elk-blog/pkg/e"
	"gitee.com/jikey/elk-blog/pkg/response"
	"github.com/flosch/pongo2"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"strconv"
)

type Banner struct {
	Base
}

func (b *Banner) Index(c *gin.Context) {
	c.HTML(200, "admin/banner/index.html", pongo2.Context{
		"title": "Welcome11222!",
		"greet": "hello",
		"obj":   "world",
	})
}

// List 列表
func (b *Banner) List(c *gin.Context) {
	data := make(map[string]interface{})

	title := c.Query("title")
	maps := "title like '%" + title + "%'"

	data["rows"] = service.Banner.List(maps)

	response.Success(c, data)
}

// Insert 新增保存
func (b *Banner) Insert(c *gin.Context) {
	banner := &model.Banner{}

	if err := c.ShouldBind(&banner); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	err := service.Banner.Create(banner)

	if err != nil {
		logrus.Error("修改失败", err)
		response.Fail(c, e.ErrorUpdate)
		return
	}

	response.Success(c, banner)
}

// Update 修改
func (b *Banner) Update(c *gin.Context) {
	banner := &model.Banner{}

	if err := c.ShouldBind(&banner); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	id := strconv.Itoa(banner.Id)
	err := service.Banner.Update(id, banner)

	if err != nil {
		logrus.Error("修改失败： ", err)
		response.Fail(c, e.ErrorUpdate)
		return
	}

	response.Success(c, banner)
}

// Destory 删除
func (b *Banner) Destory(c *gin.Context) {
	id := c.PostForm("id")
	service.Banner.Delete(id)

	response.Success(c, id, "删除成功")
}
